package com.lagouedu.kucun.miaosha.controller;

import com.lagouedu.kucun.miaosha.service.MService;
import com.lagouedu.kucun.miaosha.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class MController {

    @Autowired
    private MService mService;

    @RequestMapping("/lagouPhone/miaosha/{userId}")
    public Map miaoSha(@PathVariable String userId){

        Map map = new HashMap();
        // 1. 秒杀商品100个 首先查询redis中剩下可以秒杀的商品数量 如果秒杀完则直接返回秒杀结束
        Integer remainNum = mService.getRemainNum();
        //  1）如果库存充足则获取redission锁
        if(remainNum > 0){
            // 获取锁
            RLock lock = mService.getLock(Constants.MIAOSHA_LOCK);
            lock.lock();
            // 获取锁后重新检查库存数量
            Integer remainNum1 = mService.getRemainNum();
            if(remainNum1 > 0){
                // redis 扣减库存并发送消息
                mService.doMiaosha(userId);
                map.put("code", 200);
                map.put("msg", "恭喜"+userId+"抢购成功！");
                log.info("恭喜\"+userId+\"抢购成功！");
                return map;
            }
            // 解锁
            lock.unlock();
            map.put("code", 200);
            map.put("msg", "sorry, 库存不足");
            log.info("sorry, 库存不足");
            return map;
        }
        map.put("code", 200);
        map.put("msg", "sorry, 库存不足");
        log.info("sorry, 库存不足");
        return map;
    }
}
